package com.ushine.web.log.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author yls
 * @Date: 2020/10/20 00:10
 * @Description: 获取 IP 地址
 * @Version 1.0
 */
@Slf4j
public class IPUtils {
    private IPUtils() {
    }

    /**
     * 未知 host
     */
    private static final String UNKNOWN_HOST = "unknown";

    /**
     * 本机地址
     */
    private static final String LOCAL_HOST = "127.0.0.1";

    /**
     * 本机地址
     */
    private static final String LOCAL_HOST_IP = "0:0:0:0:0:0:0:1";


    /**
     * 功能描述:
     * 〈 获取请求的ip地址 〉
     *
     * @param request 请求
     * @return : java.lang.String
     * @author : yls
     * @date : 2022/3/7 16:53
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN_HOST.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN_HOST.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN_HOST.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (LOCAL_HOST.equals(ipAddress) || LOCAL_HOST_IP.equals(ipAddress)) {
                //根据网卡取本机配置的IP
                InetAddress inert = null;
                try {
                    inert = InetAddress.getLocalHost();
                    ipAddress = inert.getHostAddress();
                } catch (UnknownHostException e) {
                    log.info("exception:", e);
                }

            }
        }
        /*
         *对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
         * "***.***.***.***".length() = 15
         */
        // ip地址长度
        int ipLength = 15;
        // 逗号分隔符
        String split = ",";
        if (ipAddress != null && ipAddress.length() >ipLength && ipAddress.indexOf(split) > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
        return ipAddress;
    }
}
